# -*- coding:utf-8 -*-
import random

import torndb

import setting
from util import gen_uuid
from util.date_util import add_months, curr_datetime_now

class GenCode(object):

    def __init__(self):
        self.db = torndb.Connection(
            host=setting.mysql_host,
            database="hotel",
            user=setting.mysql_user,
            password=setting.mysql_password,
            time_zone="+8:00",
            charset='utf8mb4',
            max_idle_time=900,
            connect_timeout=900
        )

        self.prefix = "1001"


    def gen_rand(self, count=6):
        str = ""
        for i in range(count):
            ch = chr(random.randrange(ord('0'), ord('9') + 1))
            str += ch

        return str

    def insert(self, distributor_company_id, manufacturer_company_id):
        due_time = add_months(curr_datetime_now(), 12)
        params = {"id": gen_uuid(), "code": self.prefix + self.gen_rand(), "due_time": due_time, "distributor_company_id": distributor_company_id, "manufacturer_company_id": manufacturer_company_id}
        self.db.execute("insert into t_hotel_code (id, code, due_time, distributor_company_id, manufacturer_company_id, allot_time, create_date, update_date) "
                        "values (%(id)s, %(code)s, %(due_time)s, %(distributor_company_id)s, %(manufacturer_company_id)s, now(), now(), now())", **params)

    def gen_code(self, count=0, distributor_company_id="", manufacturer_company_id=""):

        if not distributor_company_id:
            print "plz input distributor_company_id"
            return

        if not manufacturer_company_id:
            print "plz input manufacturer_company_id"
            return

        if count > 0:
            for i in range(count):
                print i
                self.insert(distributor_company_id, manufacturer_company_id)
        else:
            print "plz input count"

if __name__ == '__main__':
    gen = GenCode()
    gen.gen_code(100, distributor_company_id="fb08824a1a0c4864b91d2bbb6af50c9f", manufacturer_company_id="f5b9bf35f70e4d6cb1ef9a71067ed2fd")